import React, { useState, useRef, useEffect } from 'react';
import {
    View,
    Text,
    TextInput,
    StyleSheet,
    TouchableOpacity,
    Modal,
    Button,
    Keyboard,
    Image,
    Alert
} from 'react-native';
import { useRouter } from 'expo-router';
import { useRoute } from '@react-navigation/native';
import { useDispatch } from 'react-redux'; // 引入 useDispatch
import { addPayment } from '../../store/paymentSlice'; // 引入 Redux 的 action
import { updateVipStatus } from '../../store/userSlice'
import { updateTrastionion } from '../../store/userTranslation'
import { updateTranslationPackage } from '@/store/userTranslationSlice'

export default function PaymentScreen() {
    const [password, setPassword] = useState(''); // 保存支付密码
    const [showModal, setShowModal] = useState(false); // 控制弹出框显示
    const passwordInputRef = useRef(null);
    const [paymentInfo, setPaymentInfo] = useState(null);
    const router = useRouter();
    const response = useRoute().params;
    const dispatch = useDispatch(); // 初始化 Redux 的 dispatch
    const correctPaymentPassword = '123456';

    const handlePayment = () => {
        setShowModal(true); // 显示弹出框
        setTimeout(() => {
            passwordInputRef.current?.focus(); // 自动聚焦输入框，弹出数字键盘
        }, 100);
    };


    useEffect(() => {
        if (response) {
            setPaymentInfo(response);
        }
    }, [response]);
    const handleConfirmPayment = () => {
        if (password.length === 6) {
            if (password === correctPaymentPassword) {
                //存储content price duration time 
                const order = {
                    id: new Date().toISOString(), // 使用时间戳作为唯一 ID
                    content: paymentInfo.content,
                    price: paymentInfo.price,
                    time: new Date().toLocaleString(), // 支付时间
                    duration: paymentInfo.duration || null,
                };

                const now = new Date();

                // 假设 order.duration 是 "1个月" 或 "3个月"
                const durationStr = order.duration; // 例如 "1个月" 或 "3个月"

                // 提取数字部分并转换为整数
                const durationMonths = parseInt(durationStr, 10);

                // 假设一个月平均为 30 天
                const daysPerMonth = 30;
                const millisecondsPerMinute = 60 * 1000; // 一分钟的毫秒数
                // const millisecondsPerHour = 60 * millisecondsPerMinute; // 一小时的毫秒数
                // const millisecondsPerDay = 24 * millisecondsPerHour; // 一天的毫秒数
                // const millisecondsPerMonth = daysPerMonth * millisecondsPerDay; // 一个月的毫秒数

                // 计算vip到期日期
                const expirationDate = new Date(now.getTime() + millisecondsPerMinute);

                //计算翻译包到期日期
                const translationExpirationDate = new Date(now.getTime() + millisecondsPerMinute);

                // 根据支付内容更新状态
                if (paymentInfo.content === 'vip') {
                    // 只在购买VIP时更新VIP状态
                    dispatch(updateVipStatus({ isVip: true, expirationDate: expirationDate.toISOString() }));
                }

                if (paymentInfo.content === '翻译包') {
                    // 只在购买翻译包时更新翻译包状态
                    dispatch(updateTrastionion({ isTraslation: true, translationDate: translationExpirationDate.toISOString() }));
                    dispatch(updateTranslationPackage(true));
                }
                // 将订单数据存储到 Redux
                dispatch(addPayment(order));
                router.push({
                    pathname: '/my/success',
                    params: { amount: paymentInfo.price },
                });
            } else {
                setPassword(''); // 清空密码
                Alert.alert('支付失败', '支付密码错误');
            }
            setShowModal(false);
            Keyboard.dismiss(); // 隐藏键盘
        } else {
            setPassword(''); // 清空密码
            Alert.alert('支付失败', '请输入完整的6位支付密码');
        }
    };

    const handleCloseModal = () => {
        setShowModal(false); // 关闭弹出框
        setPassword(''); // 清空密码
        Keyboard.dismiss(); // 隐藏键盘
    };

    return (
        <View style={styles.container}>
            <View style={styles.headerLeft}>
                <TouchableOpacity onPress={() => router.back()}>
                    <Image source={require('../../assets/images/back.png')} style={styles.headerImg} />
                </TouchableOpacity>
                <Text style={styles.title}>支付</Text>
                <Text style={styles.title}></Text>
            </View>

            {/* 显示支付信息 */}
            {paymentInfo && (
                <View style={styles.paymentInfoContainer}>
                    <View style={styles.paymentDetailsContainer}>
                        <Text style={styles.paymentDetails}>{paymentInfo.description}
                        </Text>
                        {
                            paymentInfo.content === 'vip' ? <Text style={styles.paymentDetails}>vip</Text> : ''
                        }
                        {
                            paymentInfo.content === '钻石' ? <View style={styles.paymentDetails}>
                                <Image source={require('../../assets/images/diamond.png')} style={styles.diamondImg} />
                            </View> : ''
                        }
                    </View>
                    <Text style={styles.paymentDetailsaaa}>¥{paymentInfo.price}</Text>
                </View>
            )}
            {/* 模拟支付按钮 */}
            <Button title="立即支付" onPress={handlePayment} />

            {/* 支付密码弹出框 */}
            <Modal
                visible={showModal}
                animationType="slide"
                transparent={true}
                onRequestClose={handleCloseModal}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>请输入支付密码</Text>

                        {/* 支付密码输入框 */}
                        <TextInput
                            ref={passwordInputRef}
                            style={styles.passwordInput}
                            value={password}
                            onChangeText={setPassword}
                            keyboardType="numeric" // 数字键盘
                            secureTextEntry={true} // 密码隐藏
                            maxLength={6} // 限制为6位
                            placeholder="请输入6位支付密码"
                            placeholderTextColor="#ccc"
                        />

                        {/* 确认按钮 */}
                        <TouchableOpacity
                            style={styles.confirmButton}
                            onPress={handleConfirmPayment}
                        >
                            <Text style={styles.confirmButtonText}>确认支付</Text>
                        </TouchableOpacity>

                        {/* 取消按钮 */}
                        <TouchableOpacity style={styles.cancelButton} onPress={handleCloseModal}>
                            <Text style={styles.cancelButtonText}>取消</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    diamondImg: {
        width: 20,
        height: 20,
    },
    paymentDetailsContainer: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
    },
    paymentDetailsaaa: {
        fontSize: 25,
        fontWeight: 'bold',
    },
    paymentInfoContainer: {
        display: 'flex',
        marginTop: 20,
        marginBottom: 20,
        alignItems: 'center',
        marginLeft: 10,
    },
    container: {
        width: '100%',
        flex: 1,
        padding: 20,
        backgroundColor: '#fff',
    },
    headerImg: {
        width: 25,
        height: 25,
        marginRight: 10,
        marginLeft: 10,
    },
    headerLeft: {
        marginTop: 12,
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: 280,
        marginBottom: 20,
    },
    title: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    paymentDetails: {
        fontSize: 16,
        marginBottom: 10,
        fontWeight: 'bold',
    },
    amountInput: {
        width: '100%',
        height: 60,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 8,
        paddingHorizontal: 10,
        fontSize: 18,
        marginBottom: 30,
        backgroundColor: '#f9f9f9',
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)', // 半透明背景
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        width: '80%',
        backgroundColor: '#fff',
        padding: 20,
        borderRadius: 10,
        alignItems: 'center',
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    passwordInput: {
        width: '100%',
        height: 50,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 8,
        paddingHorizontal: 10,
        fontSize: 18,
        textAlign: 'center',
        marginBottom: 20,
        backgroundColor: '#f9f9f9',
    },
    confirmButton: {
        backgroundColor: '#4CAF50',
        paddingVertical: 10,
        paddingHorizontal: 30,
        borderRadius: 5,
        marginBottom: 10,
    },
    confirmButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    cancelButton: {
        marginTop: 10,
    },
    cancelButtonText: {
        color: '#999',
        fontSize: 14,
    },
});
